package br.org.credfaz.ficha.utils;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;


import br.org.credfaz.ficha.Db2ConnectionFactory;
import br.org.credfaz.ficha.modelo.PlanoPagamento;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

public class CalculaDias {
	
	private final Connection connection;

	public CalculaDias() {
		try {
			connection = new Db2ConnectionFactory().getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public PlanoPagamento buscaPorId(Long id) throws java.text.ParseException{
		try {
			PreparedStatement stmt = this.connection
					.prepareStatement("select * from planopagamento where idcliente = ?");
			stmt.setLong(1, id);

			ResultSet rs = stmt.executeQuery();

			if (rs.next()) {
				return calculaDias(rs);
			}

			rs.close();
			stmt.close();

			return null;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public PlanoPagamento calculaDias(ResultSet rs) throws java.text.ParseException, SQLException {
		//SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		
		PlanoPagamento ppag = new PlanoPagamento();
		
		ppag.setIdcliente(rs.getLong("idcliente"));
		ppag.setNumcontratocredito(rs.getFloat("numcontratocredito"));
		ppag.setNumparcela(rs.getInt("numparcela"));
		ppag.setValorjurosparcela(rs.getDouble("valorjurosparcela"));
		ppag.setQtddiasjurosoperacao(rs.getLong("qtddiasjurosoperacao"));
		ppag.setDatavencparcela(rs.getDate("datavencparcela"));
		ppag.setValorsaldodevedorinicial(rs.getDouble("valorsaldodevedorinicial"));
		
		Date d1 = null;
		try {
			d1 = new Date();
		} catch (ParseException ex) {
			ex.printStackTrace();
		}
		Date d2 = null;
		try {
			d2 = ppag.getDatavencparcela();
		} catch (ParseException ex) {
			ex.printStackTrace();
		}
		
		long dt = (d2.getTime() - d1.getTime()) + 3600000;
		long hd = (dt / 86400000L) + 1;
		
		long hdq = ppag.getQtddiasjurosoperacao() - hd;
		double vhdq = (ppag.getValorjurosparcela() / ppag.getQtddiasjurosoperacao()) * hdq;
		double saldodevedor = vhdq + ppag.getValorsaldodevedorinicial();
		
		ppag.setSaldodevedor(saldodevedor);
		
		return ppag;
	}
}
